<template>
  <view>
    <hx-navbar ref="hxnb" :config="config" @clickBtn="clickBtn"></hx-navbar>
    <view class="time-view">
      {{ time }}
    </view>
    <view class="form-view">
      <view class="form-item" @click="go('/pages/application/pages/personnel/custom/custom', { isJump: true })">
        <view class="label blue">
          客户
        </view>
        <view class="value" :class="listData.auditState == true && listData.isCancel == false ? 'c-99' : ''">
          <text>{{ listData.comegoName }}</text>
        </view>
      </view>
      <view class="form-item" @click="go('/pages/application/pages/personnel/staff/staff', { isJump: true })">
        <view class="label">
          业务员
        </view>
        <view class="value" :class="listData.auditState == true && listData.isCancel == false ? 'c-99' : ''">
          <text>{{ listData.handUserName }}</text>
        </view>
      </view>
      <view class="form-item">
        <view class="label">
          调整金额
        </view>
        <view class="value" :class="listData.auditState == true && listData.isCancel == false ? 'c-99' : ''">
          <u--input @change="change" @input="changInput"
            :color="listData.auditState == true && listData.isCancel == false ? '#999' : ''"
            :disabled="listData.auditState == true && listData.isCancel == false" v-model="listData.amount" placeholder=""
            border="none"></u--input>
        </view>
      </view>
      <view class="form-item">
        <view class="label">
          金额大写
        </view>
        <view class="value" :class="listData.auditState == true && listData.isCancel == false ? 'c-99' : ''">
          <text>{{ amountDX }}</text>
        </view>
      </view>

      <view class="form-item">
        <view class="flex col-item">
          <view class="label">
            前欠
          </view>
          <view class="value" :class="listData.auditState == true && listData.isCancel == false ? 'c-99' : ''">
            {{ listData.comegoCurrentDebt || 0 }}
          </view>
        </view>
        <view class="flex col-item">
          <view class="label">
            累欠
          </view>
          <view class="value" :class="listData.auditState == true && listData.isCancel == false ? 'c-99' : ''">
            {{ listData.comegoTotalDebt || 0 }}
          </view>
        </view>
      </view>
      <view class="form-item"
        @click="go('/pages/application/pages/finance/accounts-receivable-payable/components/business-reconciliation-types')">
        <view class="label blue">
          类型
        </view>
        <view class="value" :class="listData.auditState == true && listData.isCancel == false ? 'c-99' : ''">
          {{ listData.typeName }}
        </view>
      </view>
      <view class="form-item">
        <view class="label">
          备注
        </view>
        <view class="value">
          <u--input :color="listData.auditState == true && listData.isCancel == false ? '#999' : ''"
            :disabled="listData.auditState == true && listData.isCancel == false" @input="changInput"
            v-model="listData.remarks" placeholder="" border="none"></u--input>
        </view>
      </view>
    </view>
    <view class="fixed-btn flex">

      <!-- 详情、编辑 -->
      <u-button v-if="listData.auditState == false && listData.isCancel == false && id" text="审核" @click="audits()"
        type="primary" shape="circle" color="#ff9b00" border="none"></u-button>

      <u-button v-if="listData.auditState == true && listData.isCancel == false" text="作废"
        @click="() => { cancelShow = true }" type="primary" shape="circle" color="#8d97a5"></u-button>


      <u-button v-if="listData.auditState == false && listData.isCancel == false && id == null" text="保存"
        @click="updateItemData(1)" type="primary" shape="circle"
        color="linear-gradient(to right, rgb(64, 158, 255), rgb(64, 158, 255), rgb(96, 180, 246), rgb(96, 180, 246))"></u-button>


      <u-button v-if="listData.auditState == null && listData.isCancel == null && !id" text="保存" @click="save()"
        type="primary" shape="circle"
        color="linear-gradient(to right, rgb(64, 158, 255), rgb(64, 158, 255), rgb(96, 180, 246), rgb(96, 180, 246))"></u-button>
    </view>
    <!-- 客户选择弹框 -->
    <u-popup :show="isLikeShow" mode="center" :round="5" @close="onLikeClose" :closeOnClickOverlay="true">
      <view class="pop-ul">
        <view class="pop-li" :class="{ 'active': listData.comegoTypeId == item.value }" v-for="(item, index) in optList"
          :key="index" @click="onCheck(item)">
          <u-icon name="checkbox-mark" color="#fff" class="m-r-20" size="24"
            v-if="listData.comegoTypeId == item.value"></u-icon>
          {{ item.label }}
        </view>
      </view>
    </u-popup>
    <u-popup class="u-pop" :show="cancelShow" :round="10" mode="center" :closeOnClickOverlay="false">
      <view class="popup-view">
        <view class="title" style="line-height: 282rpx;">
          您确定要作废当前单据吗?
        </view>
        <view class="bot-view flex flex-sa">
          <view class="btn" @click="() => { cancelShow = false }">
            取消
          </view>
          <view class="btn" @click="cancels(false)">
            直接作废
          </view>
          <view class="btn" @click="cancels(true)">
            重新做单
          </view>
        </view>
      </view>
    </u-popup>
    <u-toast ref="uToast"></u-toast>
    <cx-delete-data
      @close="
        () => {
          deleteShow = false;
        }
      "
      :show="deleteShow"
      :id="listData.id"
      @delectDatalist="delectDatalist"
    ></cx-delete-data>
  </view>
</template>

<script>
import clIcon from "@/components/cl-icon/cl-icon.vue";
import { date, convertToChineseNumber } from '@/utils/util.js'
import { initAddBill, getLastRemainDebtTotal, addData, audit, getViewDataByBillId, cancel, updateData,deleteById } from "@/apis/bill/business-reconciliation";
import { comeGoType } from "@/apis/bill/payment-order";
import cxDeleteData from "@/components/cx-delete-data/cx-delete-data.vue";
export default {
  components: {
    clIcon,
    cxDeleteData
  },
  data() {
    return {
      isLikeShow: false,
      optList: [],
      time: '',
      config: {
        title: "业务调账",
        color: "#ffffff",
        navigateBack: 1, // 返回的页面数  默认为1 返回上级  2返回上2级  3返回上3级
        // backTabPage:'', // 跳转到tab传这个参数
        // backPage:'', // 跳转到其他页面传这个参数
        //背景颜色;参数一：透明度（0-1）;参数二：背景颜色（array则为线性渐变，string为单色背景）
        backgroundColor: [1, ["#409EFF", "#409EFF", "#60b4f6", "#60b4f6"]],
        rightButton: [
          {
            key: "btn1",
            icon: "&#xe646;",
            position: "left",
          },
          {
            key: "btn2",
            txt: "",
            icon: "&#xed34;",
            // position: "left",
          },
        ],
      },
      listData: {
        // "id": "",
        // "billNo": "",
        // "shopId": "",
        // "shopName": "总部",
        // "businessTime": "",
        // "comegoTypeId": 0,
        // "comegoTypeName": "",
        // "comegoId": "",
        // "comegoName": "",
        // "comegoCurrentDebt": 0,
        // "comegoTotalDebt": 0,
        // "amount": 0,
        // "remarks": null,
        // "isCancel": null,
        // "cancelTime": null,
        // "cancelUserId": null,
        // "cancelUserName": null,
        // "cancelCause": null,
        // "auditState": null,
        // "auditTime": null,
        // "auditUserId": null,
        // "auditUserName": null,
        // "handUserId": "",
        // "handUserName": "",
        // "createUserId": "",
        // "createUserName": "",
        // "createTime": "",
        // "updateTime": "",
        // "updateUserId": "",
        // "updateUserName": "",
        // typeId: "",
        // typeName: ""
      },
      id: null,
      //type 控制是否清空id
      type: 1,
      amountDX: '',
      index: 0,
      // 作废按钮
      cancelShow: false,
      deleteShow:false
    };
  },
  computed: {

  },
  onLoad(opt) {
    this.getComeGoType()
    if (this.$Route.query.id) {
      this.type = 1
      this.id = this.$Route.query.id
      this.getViewDataByBillIds()
    } else {
      this.initAddBills()
    }
  },

  onShow() { },
  methods: {
    clickBtn(item) {
      if (item.key === "btn1") {
        // this.printShow = true;
      } else if (item.key === "btn2") {
        this.deleteShow = !this.deleteShow;
      }
    },
   // 删除收款单
    delectDatalist() {
      let _this = this;
      _this.deleteShow = false;
      uni.showModal({
        content: "您确认删除当前单据吗?",
        success: function (res) {
          if (res.confirm) {
            deleteById(_this.listData.id).then((res) => {
              if (!res.flag) return;
              _this.$refs.uToast.show({
                type: "success",
                title: "",
                message: "删除成功",
                complete() {
                  uni.switchTab({
                    url: "/pages/application/index",
                  });
                },
              });
            });
          } else if (res.cancel) {
          }
        },
      });
    },
    change(e) {
      this.amountDX = convertToChineseNumber(e)
    },
    // 获取供应商opts
    getComeGoType() {
      comeGoType().then(res => {
        if (!res.flag) return;
        this.optList = res.data;
      })
    },
    // 显示客户置
    onLikeSet() {
      this.isLikeShow = true;
    },
    // 设置客户设置
    onCheck(val) {
      this.listData.comegoTypeName = val.label;
      this.listData.comegoTypeId = val.value;
      this.listData.comegoName = ''
      this.onLikeClose()
    },
    onLikeClose() {
      this.isLikeShow = false;
    },
    changInput() {
      if (this.listData.auditState == false && this.listData.isCancel == false && this.id && this.type != 1) {
        this.id = null
      }
    },
    // 获取当前订单和时间
    getViewDataByBillIds() {
      getViewDataByBillId(this.id).then((res) => {
        if (!res.flag) return;
        const data = res.data || {};
        this.id = data.id
        this.listData = data
      });
    },
    cancels(show) {
      this.cancelShow = false
      cancel({
        billId: this.id,
        isGenerateSameBill: show
      }).then((res) => {
        if (!res.flag) return;
        const data = res.data || {};
        if (show) {
          this.id = null
          this.listData.isCancel = null
          this.listData.auditState = null
          // this.getViewDataByBillIds()
        } else {
          this.$refs.uToast.show({
            type: 'success',
            title: '',
            message: "作废成功",
            complete() {
              uni.switchTab({
                url: '/pages/application/index'
              });
            }
          })
        }
      });
    },
    audits() {
      let _this = this
      uni.showModal({
        content: '您确认审核当前单据吗?',
        success: function (res) {
          if (res.confirm) {
            audit(_this.id).then((res) => {
              if (!res.flag) return;
              const data = res.data || {};
              _this.id = data.id
              _this.type = 2
              _this.getViewDataByBillIds()
              _this.$refs.uToast.show({
                type: 'success',
                title: '',
                message: "审核成功",
              })
            });
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    },
    // 修改
    updateItemData(i) {
      updateData(this.listData).then((res) => {
        if (!res.flag) return;
        const data = res.data || {};
        this.id = data.id
        if (i == 0) {
          this.audits()
        } else {
          this.getViewDataByBillIds()
          this.$refs.uToast.show({
            type: 'success',
            title: '',
            message: "保存成功",
          })
        }

      });
    },
    save() {
      addData(this.listData).then((res) => {
        if (!res.flag) return;
        const data = res.data || {};
        this.id = data.id
        this.type = 1
        this.getViewDataByBillIds()
        this.$refs.uToast.show({
          type: 'success',
          title: '',
          message: "保存成功",
        })

      });
    },
    // 页面跳转
    go(item, query = {} || []) {
      if (this.listData.auditState == true && this.listData.isCancel == false) {
        return
      }
      this.$Router.push({
        path: item,
        query: query
      });
    },
    getDocument(item) {
      if (this.listData.auditState == true && this.listData.isCancel == false) {
        return
      }
      if (!this.listData.comegoId) {
        uni.showToast({
          icon: 'error',
          title: '请先选择客户'
        })
        return
      }
      this.$Router.push({
        path: item,
        query: {
          id: this.listData.comegoId,
          type: 2
        }
      });
    },
    // 获取当前订单和时间
    initAddBills() {
      initAddBill().then((res) => {
        if (!res.flag) return;
        const data = res.data || {};
        this.listData = data
      });
    },
    // 查询当前欠款
    getLastRemainDebtTotals() {
      getLastRemainDebtTotal({
        "customerId": this.listData.comegoId,
        "businessTime": this.listData.businessTime
      }).then((res) => {
        if (!res.flag) return;
        const data = res.data;
        this.listData.comegoCurrentDebt = data
        this.listData.comegoTotalDebt = data
      });
    },
  },
  mounted() {
    this.time = date('Y-m-d H:i:s', new Date());

    uni.$on('pushCustomDetails', data => {
      this.listData.comegoId = data.id
      this.listData.comegoName = data.name
      this.getLastRemainDebtTotals()
      this.changInput()
    })
    uni.$on('on-staff-custom-details', data => {
      this.listData.handUserId = data.id
      this.listData.handUserName = data.realName
      this.changInput()
    })

    uni.$on('on-business-reconciliation-types', data => {
      this.listData.typeId = data.value
      this.listData.typeName = data.label
    })
  },

  beforeDestroy() {
    uni.$off("pushCustomDetails");
    uni.$off("on-staff-custom-details");
    uni.$off("receiptSelectBank");
    uni.$off("on-receipt-other-expenses");
    uni.$off("on-business-reconciliation-types");
  },
};
</script>


<style lang="scss" scoped>
.fixed-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx 20rpx;
  background: #fafafa;

  .card-btn {
    color: #409eff !important;
    border-radius: 40rpx 0 0 40rpx;
  }

  .save-btn {
    border-radius: 40rpx;
  }
}

.time-view {
  background: linear-gradient(to right, rgb(64, 158, 255), rgb(64, 158, 255), rgb(96, 180, 246), rgb(96, 180, 246));
  text-align: center;
  padding: 20rpx 0 30rpx;
  color: rgba(255, 255, 255, 0.6);
}

.form-view {
  background: #fff;
  overflow: hidden;

  .form-item {
    display: flex;
    border-bottom: 1rpx solid #ddd;
    padding: 24rpx 40rpx;
    align-items: center;
    font-size: 30rpx;

    .label {
      color: #999;
      flex: 1.5;
      text-align: right;
      padding-right: 18rpx;
    }

    .value {
      flex: 6;
      display: flex;
      min-width: 100px;
      height: 20px;
    }

    .category {
      justify-content: space-between;
    }

    .col-item {
      flex: 1;

      .value {
        flex: 2.4;
        min-width: 100px;
        height: 20px;
      }
    }
  }
}
</style>